package com.example.customconsume.component.chain;

import com.example.customconsume.component.CustomPayHandler;
import com.example.customconsume.entity.ConsumeDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @Description 处理器链（上下文）默认实现
 * @Author lihw
 * @Date 2024/7/10 14:45
 */
@Slf4j
@Component
public class DefaultHandlerChainImpl implements HandlerChain {
    private final List<CustomPayHandler<ConsumeDto>> customPayHandlers;

    public DefaultHandlerChainImpl(List<CustomPayHandler<ConsumeDto>> customPayHandlers) {
        this.customPayHandlers = customPayHandlers;
    }

    ThreadLocal<Integer> currentHandlerIndex = new ThreadLocal<>();
    ThreadLocal<Integer> totalHandlerIndex = new ThreadLocal<>();

    @Override
    public void doHandler(ConsumeDto consumeDto) {
        Integer current = currentHandlerIndex.get();
        Integer total = totalHandlerIndex.get();
        if (current == null) {
            current = 0;
        }
        if (total == null) {
            total = customPayHandlers.size();
        }
        if (current < total) {
            CustomPayHandler<ConsumeDto> customPayHandler = customPayHandlers.get(current++);
            currentHandlerIndex.set(current);
            totalHandlerIndex.set(total);
            customPayHandler.handleCustomPay(consumeDto, this);
        } else {
            log.info("未找到合适的处理器");
        }

    }
}
